﻿using System;
using System.Net.Mail;
using System.Text;
using Argotic.Syndication.Specialized;
using Dexter.Logger.Contracts;

namespace Dexter.Services.Implementation
{
	internal static class BlogMlImportServiceHelpers
	{
		/// <summary>
		/// 	Decodes the content of the blog ML text constructut.
		/// </summary>
		/// <param name = "construct">The construct.</param>
		/// <returns></returns>
		internal static string DecodeBlogMlTextConstructutContent(BlogMLTextConstruct construct)
		{
			if (construct == null)
				return string.Empty;

			switch (construct.ContentType)
			{
				case BlogMLContentType.Base64:
					return DecodeBase64String(construct.Content);
				default:
					// Text and other not handled content types
					return construct.Content;
			}
		}

		internal static string DecodeBase64String(string encodedData)
		{
			byte[] encodedDataAsBytes = Convert.FromBase64String(encodedData);
			string returnValue = Encoding.ASCII.GetString(encodedDataAsBytes);
			return returnValue;
		}

		internal static MailAddress GetMailAddressSafe(string email, ILogger logger)
		{
			try
			{
				if (!string.IsNullOrEmpty(email))
					return new MailAddress(email);
			}
			catch
			{
				// in case of exception we use the default one
				if (logger != null)
					logger.WarnFormat("ERROR: Tried to import an invalid email '{0}', using default", email);
			}
			return new MailAddress("unavailable@dexter.com");
		}
	}
}
